﻿using System;
using System.IO;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.FileProviders;
using Microsoft.Net.Http.Headers;

namespace ZilLion.Service.Core.Starter.Config
{
    public class StaticConfig
    {
        public static void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            var contentRoot = AppDomain.CurrentDomain.BaseDirectory;
            var viewspath = Path.Combine(contentRoot, "views");
            var staticspath = Path.Combine(contentRoot, "views", "static");

            if (Directory.Exists(viewspath) && Directory.Exists(staticspath))
            {
                IFileProvider fileProvider = new PhysicalFileProvider(viewspath);
                IFileProvider staticProvider = new PhysicalFileProvider(staticspath);

                app.UseDefaultFiles(new DefaultFilesOptions
                {
                    RequestPath = PathString.Empty,
                    FileProvider = fileProvider
                });

                app.UseStaticFiles(new StaticFileOptions
                {
                    FileProvider = staticProvider,
                    RequestPath = "/static",
                    OnPrepareResponse = context =>
                    {
                        const int durationInSeconds = 60 * 60;
                        context.Context.Response.Headers[HeaderNames.CacheControl] =
                            "public,max-age=" + durationInSeconds;

                        //if (headers.ContentType.MediaType == "application/x-gzip")
                        //{
                        //    if (context.File.Name.EndsWith("js.gz"))
                        //    {
                        //        headers.ContentType = new MediaTypeHeaderValue("application/javascript");
                        //    }
                        //    else if (context.File.Name.EndsWith("css.gz"))
                        //    {
                        //        headers.ContentType = new MediaTypeHeaderValue("text/css");
                        //    }

                        //    context.Context.Response.Headers.Add("Content-Encoding", "gzip");
                        //}
                    }
                });
                app.UseStaticFiles(new StaticFileOptions
                {
                    FileProvider = fileProvider,
                    RequestPath = PathString.Empty,
                });
            }

          
        }
    }
}